﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;


namespace advadev.CanOpen
{

    /// <summary>
    /// Represents a process data object write transfer
    /// </summary>
    public class ProcessDataObjectWriteTransfer : ITransfer
    {

        /// <summary>for internal use</summary>
        private bool _isProducerTransfer;
        /// <summary>for internal use</summary>
        private bool _isTransferCompleteAfterSending;
        /// <summary>for internal use</summary>
        private uint _pdoIndex;
        /// <summary>for internal use</summary>
        private CanOpenMessage _receivedCanOpenMessage;
        /// <summary>for internal use</summary>
        private ICanOpenObjectDictionaryContainer _canOpenObjectDictionaryContainer;
        /// <summary>for internal use</summary>
        private Collection<CanOpenMessage> _pendingSendMessages = new Collection<CanOpenMessage>();
        /// <summary>for internal use</summary>
        private ReadOnlyCollection<CanOpenMessage> _pendingSendMessagesReference;
        /// <summary>
        /// Default PDO 1 transmit COB-ID
        /// </summary>
        static public readonly UInt16 DefaultPDO1TransmitCobId = 0x180;
        /// <summary>
        /// Default PDO 2 transmit COB-ID
        /// </summary>
        static public readonly UInt16 DefaultPDO2TransmitCobId = 0x280;
        /// <summary>
        /// Default PDO 3 transmit COB-ID
        /// </summary>
        static public readonly UInt16 DefaultPDO3TransmitCobId = 0x380;
        /// <summary>
        /// Default PDO 4 transmit COB-ID
        /// </summary>
        static public readonly UInt16 DefaultPDO4TransmitCobId = 0x480;
        /// <summary>
        /// Default PDO 1 receive COB-ID
        /// </summary>
        static public readonly UInt16 DefaultPDO1ReceiveCobId = 0x200;
        /// <summary>
        /// Default PDO 2 receive COB-ID
        /// </summary>
        static public readonly UInt16 DefaultPDO2ReceiveCobId = 0x300;
        /// <summary>
        /// Default PDO 3 receive COB-ID
        /// </summary>
        static public readonly UInt16 DefaultPDO3ReceiveCobId = 0x400;
        /// <summary>
        /// Default PDO 4 receive COB-ID
        /// </summary>
        static public readonly UInt16 DefaultPDO4ReceiveCobId = 0x500;


        /// <summary>
        /// Initializes a new instance of the ProcessDataObjectWriteTransfer
        /// class by the given parameter
        /// </summary>
        /// <param name="receivedCanOpenMessage">
        /// Received can open message
        /// </param>
        /// <param name="canOpenObjectDictionaryContainer">
        /// Can open object dictionary container
        /// </param>
        /// <param name="pdoIndex">
        /// PDO index
        /// </param>
        private ProcessDataObjectWriteTransfer(CanOpenMessage receivedCanOpenMessage, ICanOpenObjectDictionaryContainer canOpenObjectDictionaryContainer, uint pdoIndex)
        {
            _isProducerTransfer = false;
            _pdoIndex = pdoIndex;
            _receivedCanOpenMessage = receivedCanOpenMessage;
            _canOpenObjectDictionaryContainer = canOpenObjectDictionaryContainer;
        }

        /// <summary>
        /// Initializes a new instance of the ProcessDataObjectWriteTransfer
        /// class by the given parameter
        /// </summary>
        /// <param name="canOpenValueObjects">
        /// List of can open value objects to send in the transfer
        /// </param>
        /// <param name="nodeId">
        /// Node id of the device that writes the PDO (must be in the range of
        /// 1..127)
        /// </param>
        /// <param name="cobId">
        /// COB-ID
        /// </param>
        /// <exception cref="ArgumentNullException">
        /// Will be thrown if the list of can open value objects is null
        /// </exception>
        /// <exception cref="ArgumentOutOfRangeException">
        /// Will be thrown if the node id is not in the range of 1..127
        /// </exception>
        public ProcessDataObjectWriteTransfer(IList<ICanOpenValueObject> canOpenValueObjects, byte nodeId, UInt16 cobId)
        {
            // check parameter
            if (canOpenValueObjects == null)
            {
                throw new ArgumentNullException("canOpenValueObjects");
            }
            if (!(1 <= nodeId && nodeId <= 127))
            {
                throw new ArgumentOutOfRangeException("nodeId", "The node id must be in the range of 1..127");
            }

            // initializaton
            _isProducerTransfer = true;
            NodeId = nodeId;
            CobId = cobId;
            CanOpenValueObjects = canOpenValueObjects;
        }


        /// <summary>
        /// Gets or sets the node id
        /// </summary>
        private byte NodeId
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the COB-ID
        /// </summary>
        private UInt16 CobId
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the list of can open value objects
        /// </summary>
        private IList<ICanOpenValueObject> CanOpenValueObjects
        {
            get;
            set;
        }


        /// <summary>
        /// Checks if the given received can open message is a PDO write
        /// transfer request and if so it returns as out parameter a matching
        /// PDO write transfer instance
        /// </summary>
        /// <param name="receivedCanOpenMessage">
        /// Received can open message
        /// </param>
        /// <param name="canOpenObjectDictionaryContainer">
        /// Can open object dictionary container
        /// </param>
        /// <param name="processDataObjectWriteTransfer">
        /// A matching PDO write transfer instance
        /// </param>
        /// <param name="pdoIndex">
        /// The index of the received PDO
        /// </param>
        /// <param name="processDataObjectReceiveCommunicationCobIdParameterList">
        /// List of PDO receive communication COB-ID parameter
        /// </param>
        /// <returns>
        /// True if the received can open message is a PDO write transfer
        /// request, false otherwise
        /// </returns>
        static public bool IsProcessDataObjectWriteTransfer(CanOpenMessage receivedCanOpenMessage, ICanOpenObjectDictionaryContainer canOpenObjectDictionaryContainer, out ProcessDataObjectWriteTransfer processDataObjectWriteTransfer, out uint pdoIndex, IList<CanOpenUnsigned> processDataObjectReceiveCommunicationCobIdParameterList)
        {
            // check parameter
            if (receivedCanOpenMessage == null || canOpenObjectDictionaryContainer == null || processDataObjectReceiveCommunicationCobIdParameterList == null)
            {
                processDataObjectWriteTransfer = null;
                pdoIndex = 0;
                return false;
            }

            // get PDO index
            pdoIndex = 1000;
            foreach (CanOpenUnsigned cobIdParameter in processDataObjectReceiveCommunicationCobIdParameterList)
            {
                byte valid = (byte)((cobIdParameter.Value & 0x80000000) >> 31);
                if (valid == 0)
                {
                    UInt16 cobId = (UInt16)(cobIdParameter.Value & 0x1FFFFFFF);
                    UInt16 nodeId = receivedCanOpenMessage.CanId;
                    nodeId -= cobId;
                    if (1 <= nodeId && nodeId <= 127)
                    {
                        pdoIndex = (uint)(cobIdParameter.Index - 0x1400);
                        break;
                    }
                }
            }
            if (!(0 <= pdoIndex && pdoIndex <= 0x1FF))
            {
                processDataObjectWriteTransfer = null;
                pdoIndex = 0;
                return false;
            }

            // create transfer
            processDataObjectWriteTransfer = new ProcessDataObjectWriteTransfer(receivedCanOpenMessage, canOpenObjectDictionaryContainer, pdoIndex);
            return true;
        }

        /// <summary>
        /// Starts the producer transfer
        /// </summary>
        private void startProducerTransfer()
        {
            List<byte> byteArray = new List<byte>();
            foreach (ICanOpenValueObject canOpenValueObject in CanOpenValueObjects)
            {
                if (canOpenValueObject != null)
                {
                    IList<byte> objectByteArray = canOpenValueObject.ToByteArray();
                    if (byteArray.Count + objectByteArray.Count > 8)
                    {
                        break;
                    }
                    byteArray.AddRange(objectByteArray);
                }
            }
            UInt16 canId = CobId;
            canId += NodeId;
            byte byte0 = (byteArray.Count > 0 ? byteArray[0] : (byte)0);
            byte byte1 = (byteArray.Count > 1 ? byteArray[1] : (byte)0);
            byte byte2 = (byteArray.Count > 2 ? byteArray[2] : (byte)0);
            byte byte3 = (byteArray.Count > 3 ? byteArray[3] : (byte)0);
            byte byte4 = (byteArray.Count > 4 ? byteArray[4] : (byte)0);
            byte byte5 = (byteArray.Count > 5 ? byteArray[5] : (byte)0);
            byte byte6 = (byteArray.Count > 6 ? byteArray[6] : (byte)0);
            byte byte7 = (byteArray.Count > 7 ? byteArray[7] : (byte)0);
            _pendingSendMessages.Add(new CanOpenMessage(canId, byte0, byte1, byte2, byte3, byte4, byte5, byte6, byte7, (uint)byteArray.Count));
            _isTransferCompleteAfterSending = true;
        }

        /// <summary>
        /// Starts the consumer transfer
        /// </summary>
        private void startConsumerTransfer()
        {
            // find matching PDO
            CanOpenUnsigned pdoMappingNumberObject = _canOpenObjectDictionaryContainer.GetCanOpenObject((UInt16)(0x1600 + _pdoIndex), 0x00) as CanOpenUnsigned;
            if (pdoMappingNumberObject == null)
            {
                TransferComplete = true;
                return;
            }

            // process data
            int numberOfProcessedBytes = 0;
            List<byte> byteArray = new List<byte>();
            if (_receivedCanOpenMessage.Length > 0)
            {
                byteArray.Add(_receivedCanOpenMessage.Byte0);
            }
            if (_receivedCanOpenMessage.Length > 1)
            {
                byteArray.Add(_receivedCanOpenMessage.Byte1);
            }
            if (_receivedCanOpenMessage.Length > 2)
            {
                byteArray.Add(_receivedCanOpenMessage.Byte2);
            }
            if (_receivedCanOpenMessage.Length > 3)
            {
                byteArray.Add(_receivedCanOpenMessage.Byte3);
            }
            if (_receivedCanOpenMessage.Length > 4)
            {
                byteArray.Add(_receivedCanOpenMessage.Byte4);
            }
            if (_receivedCanOpenMessage.Length > 5)
            {
                byteArray.Add(_receivedCanOpenMessage.Byte5);
            }
            if (_receivedCanOpenMessage.Length > 6)
            {
                byteArray.Add(_receivedCanOpenMessage.Byte6);
            }
            if (_receivedCanOpenMessage.Length > 7)
            {
                byteArray.Add(_receivedCanOpenMessage.Byte7);
            }
            for (byte subIndex = 0x01; subIndex <= Math.Min(pdoMappingNumberObject.Value, 0x40); subIndex++)
            {
                CanOpenUnsigned pdoMappingObject = _canOpenObjectDictionaryContainer.GetCanOpenObject((UInt16)(0x1600 + _pdoIndex), subIndex) as CanOpenUnsigned;
                if (pdoMappingObject != null)
                {
                    UInt16 referencedIndex = (UInt16)(((pdoMappingObject.Value & 0x00FF0000) >> 8) + ((pdoMappingObject.Value & 0xFF000000) >> 24));
                    byte referencedSubIndex = (byte)((pdoMappingObject.Value & 0x0000FF00) >> 8);
                    byte referencedBitLength = (byte)(pdoMappingObject.Value & 0x000000FF);
                    int tmp = referencedBitLength;
                    while (tmp > 0)
                    {
                        tmp -= 8;
                    }
                    if (tmp != 0)
                    {
                        break;
                    }
                    byte referencedByteLength = (byte)Math.Round(referencedBitLength / 8d);
                    if (numberOfProcessedBytes + referencedByteLength <= byteArray.Count)
                    {
                        List<byte> currentByteArray = new List<byte>();
                        for (int i = numberOfProcessedBytes; i < numberOfProcessedBytes + referencedByteLength; i++)
                        {
                            currentByteArray.Add(byteArray[i]);
                        }
                        ICanOpenValueObject referencedObject = _canOpenObjectDictionaryContainer.GetCanOpenObject(referencedIndex, referencedSubIndex);
                        if (referencedObject != null)
                        {
                            CanOpenAbortCode abortCode = null;
                            if (!referencedObject.FromByteArray(currentByteArray, out abortCode))
                            {
                                if (abortCode == null)
                                {
                                    abortCode = new CanOpenAbortCode(0x00, 0x00, 0x00, 0x00);
                                }
                                AbortCode = abortCode;
                            }
                        }
                    }
                    numberOfProcessedBytes += referencedByteLength;
                    if (numberOfProcessedBytes >= byteArray.Count)
                    {
                        break;
                    }
                }
            }

            // end transfer
            TransferComplete = true;
        }


        #region ITransfer implementation
        /// <summary>
        /// Gets a flag indicating whether the transfer is complete (after
        /// sending the pending send messages)
        /// </summary>
        public bool TransferComplete
        {
            get;
            private set;
        }

        /// <summary>
        /// Gets the abort code (null for successful transfers)
        /// </summary>
        public CanOpenAbortCode AbortCode
        {
            get;
            private set;
        }

        /// <summary>
        /// Gets the pending send messages
        /// </summary>
        public ReadOnlyCollection<CanOpenMessage> PendingSendMessages
        {
            get
            {
                if (_pendingSendMessagesReference == null)
                {
                    _pendingSendMessagesReference = new ReadOnlyCollection<CanOpenMessage>(_pendingSendMessages);
                }
                return _pendingSendMessagesReference;
            }
        }


        /// <summary>
        /// Starts the transfer
        /// </summary>
        public void Start()
        {
            if (_isProducerTransfer)
            {
                startProducerTransfer();
            }
            else
            {
                startConsumerTransfer();
            }
        }

        /// <summary>
        /// Times out the transfer
        /// </summary>
        public void TimeOut()
        {
            AbortCode = new CanOpenAbortCode(0x00, 0x00, 0x04, 0x05);
        }

        /// <summary>
        /// Finalizes the transfer
        /// </summary>
        public void FinalizeTransfer()
        {
        }

        /// <summary>
        /// Continues the transfer after sending messages
        /// </summary>
        public void ContinueAfterSendingMessages()
        {
            _pendingSendMessages.Clear();
            if (_isTransferCompleteAfterSending)
            {
                TransferComplete = true;
            }
        }

        /// <summary>
        /// Processes the received message
        /// </summary>
        /// <param name="receivedCanOpenMessage">
        /// Received can open message
        /// </param>
        /// <returns>
        /// True, if the given can open message was related to this transfer,
        /// false otherwise
        /// </returns>
        public bool ProcessReceivedMessage(CanOpenMessage receivedCanOpenMessage)
        {
            return false;
        }
        #endregion ITransfer implementation

    }

}
